<template>
  <!--回看组件-->
  <div class='live-back-box'>
    <!--我是回看页面-->
    <component :is='isLsPoScreen' :videoInfo='videoInfo' :courseInfo='courseInfo' @sendFather='childCallBack'></component>
    <!--私密直播-->
    <Private v-if='isPrivate' :privateWords='videoInfo.videoInfo.privateWords' @sendFather='childCallBack' type='lookBackCom'></Private>
    <!--白名单组件-->
    <WhiteListCom v-if='isWhiteList' type='lookBackCom' :roomVideoInfo='videoInfo' :whiteListTopTip='whiteListTopTip' :whiteListInputText='whiteListInputText' @sendFather='childCallBack' />
    <!-- 非白名单提示页 -->
    <WhiteTip v-if="isWhiteTip" :type="WhiteType"></WhiteTip>
    <!-- 弹窗提示 -->
    <DialogD :isShow="isShow" :mode="mode" @changeShowDialog="changeShowDialog">{{tips}}</DialogD>
    <!-- app手机登录验证兜底组件 -->
    <VerifyAppLogin :modeType = 'appLoginState' v-if="isVerifyAppLogin" />
  </div>
</template>

<script>
  import Private from "@/components/privateComponent";
  import LsCom from "./components/lsLookBackCom/landscapeBackCom.vue"; //横屏组件
  import PsCom from "./components/psLookBackCom/portraitScreenBackCom.vue"; //竖屏组件
  import PvCom from "@/pages/liveBackPages/components/pureVideoCom/livePureVideo.vue"; //纯净视频
  import WhiteListCom from '@/components/whiteListCom'; //白名单组件
  import VerifyAppLogin from '@/components/verifyAppLogin' //手机登录验证兜底提示页面
  import WhiteTip from '@/components/WhiteTip'; //腾讯会议非白名单提示页
  import { checkWhitelist } from '@/util/api.js';
  export default {
    components: {
      Private, //私密直播
      LsCom, //横屏组件
      PsCom, //竖屏组件
      PvCom, //纯净视频
      WhiteListCom, //白名单组件
      VerifyAppLogin,
      WhiteTip,//腾讯会议非白名单提示页
    },
    props: {},
    data() {
      return {
        videoInfo: {},
        videoId: this.$route.params.id,
        isPrivate: false, //私密直播
        isWhiteList: false, //白名单
        whiteListInputText: '', //白名单提示文字
        whiteListTopTip: '', //白名单头部提示文字
        isLsPoScreen: '', //横屏竖屏
        getPlatform:fun.getPlatform(),
        isShow: false,
        tips: '',
        courseInfo: null,
        appLoginState:'',//phoneLogin 手机号登录观看  riskPrivate  私募微服务
        isVerifyAppLogin: false,
        isWhiteTip: false,
        WhiteType: false,//用于标识腾讯会议非白名单提示页的类型
      }
    },
    computed: {
      appVisible() {
        return this.$store.state.appVisible
      }
    },
    watch:{
      '$store.state.isYk'(val){
          if(!val && window.terminal.isZxjtApp && this.appLoginState === 'phoneLogin'){//非游客
            this.isVerifyAppLogin = false;
            this.rendBack()
          }
      }
    },
    beforeRouteEnter(to, from, next) {
      next(vm => vm.from = from);
    },
    async created() {
      const videoDetail = await this.getLiveBackInfo();
      const { title, creator } = videoDetail;
      document.title = title; // 更新页面title（神策）
      // 神策打点（进入房间）
      $sensorsTrack('liveBroadcast_PageView', {
        user_nickname: this.$store.state.userInfo.nickname, 
        live_room_id: this.$route.params.id,
        live_room_name: title,
        live_room_status: '回看',
        live_room_creator: creator,
      });
    },
    mounted() {
      this.$store.dispatch("hideNav");
    },
    beforeDestroy() {
      document.title = '中信建投'; // 更新页面title（神策）
    },
    destroyed() {
      let progress =  this.$store.state.percentage
			if(progress!=0){
          this.saveProgress(progress)
			}
      this.$store.dispatch("setShowGsTip", false);
      this.$store.dispatch("getDuration", 0); //重置
      window.sessionStorage.setItem(`${this.$channel}invitCard`, JSON.stringify([])); //退出当前直播间 邀请卡数据置空
      this.$store.commit('setAppVisible', true)
      clearTimeout(this.timeId)
    },
    methods: {
      // 改变对话框状态
      changeShowDialog() {
        this.isShow = false
        const date = new Date()
        localStorage.setItem('dialogDate' + this.videoId, '' + date.getFullYear() + date.getMonth() + date.getDate())
      },
      // 动态组件渲染
      renderCom() {
        !this.videoInfo.authorizePass && this.$http.post(`/h5live/user/trace/authorize_video/save?businessId=${this.videoId}`).then(res => {
          if (res.data.code == '000000') {
            console.log('风控首次登记成功')
          } else {
            throw res.data.code
          }
        }).catch(err => {
          console.log(err, 'authorize_video err')
          this.$router.back()
        });
        if (this.videoInfo.videoInfo.mode == '0') { // 横屏
          this.isLsPoScreen = 'LsCom'
        } else if (this.videoInfo.videoInfo.mode == '3') { // 纯净视频
          this.isLsPoScreen = 'PvCom'
        } else {
          this.isLsPoScreen = 'PsCom'
        }
      },
      // 退出直播间（保存视频进度）
			saveProgress(progress){
				let params ={
					"playProcess":progress,
					"videoId":this.videoId
				}
				this.$http.post("/h5live/video/playProcess", params,{
          headers: {
            "Content-Type": "application/json"
          }
        }).then(res => {console.log(res)},
              err => {
            console.log(err);
          }
        );
			},
      childCallBack(data) {
        switch (data.type) {
          case 'successWhiteList': //关闭白名单验证
            this.isWhiteList = false;
            this.videoInfo.ext.whiteCheck = true;
            this.rendBack()
            break;
          case 'successPrivate': ///关闭私密直播
            this.isPrivate = false;
            this.videoInfo.videoInfo.isprivate = 0
            this.rendBack()
            break;
          case 'subscribeCourseSucess': 
            this.courseInfo.haveBuy = true;
            break;
          default:
            break;
        }
        
      },
      async  rendBack(){
         //  isprivate  1 私密直播   2 老版本白名单  3 手机登录观看  5新版本白名单库
          const {videoInfo,videoInfo:{ roomVideoExt2 , isprivate , partnerType, isRestrict , mode ,courseId },ext:{whiteCheck,whiteData}} = this.videoInfo;
          const {enRc,rcType,qaId,rcId} = roomVideoExt2 || {};
          let extParam = sessionStorage.getItem('extParam')
          let source = sessionStorage.getItem('source')
          //1:白名单
          let plat = await fun.initSourcePlat()
          if(source === 'hly_mini' && !extParam && plat === 'mini'){//来源如果是会路演小程序但是无extParam
            this.isWhiteTip = true
            this.WhiteType = true
            return
          }
          if( isprivate == 2 || isprivate == 5){ 
            if (!whiteCheck) {//true  验证通过  false 为不通过
              if (extParam && source === 'hly_mini' && plat === 'mini') {//来源是会路演小程序而且有extParam，校验extParam
                this.tencentWhite()
              } else {//不存在extParam，走之前白名单逻辑
                this.whiteListInputText = whiteData?.inputText || '请输入观看密码';
                this.whiteListTopTip = whiteData?.tip || '欢迎观看本直播';
                this.isWhiteList = true;
                return
              }
            }
          }
          //2:私密直播   (isRestrict 是否第一次验证   0第一次  1非第一次)
          if (isprivate == '1' && isRestrict == '0') {
            this.isPrivate = true;
            return
          }
          //3::手机登录观看
          if (isprivate == 3 && this.$store.state.isYk) {
            if (window.terminal.isZxjtApp) {
              this.appLoginState = 'phoneLogin';          
              this.isVerifyAppLogin = true;
             
              console.log('app拉起手机登录前');
              fun.ykDisposeFun() // 手机登录
              return
            } else {
              //进入直播间从底部弹出手机号码验证
            }
          }
          if (courseId) await this.handleCoursePre(videoInfo);
           //私募跳转过来?passEnRc=true
          if (this.$route.query.passEnRc) {
            if (mode == '0') { // 横屏
              this.isLsPoScreen = 'LsCom'
            } else if (mode == '3') { // 纯净视频
              this.isLsPoScreen = 'PvCom'
            } else {
              this.isLsPoScreen = 'PsCom'
            }
            return
          }
          //4:私募验证 (最后一步私募)
          if(enRc){//私募开关开
              if(rcType == 0 || rcType == 1 || rcType == 4 ){//rcType  0 普通私募 1 私募风控  4 带货
                let source = sessionStorage.getItem('source')
                let targetUrl = encodeURIComponent(fun.getCurPageUrl('back',this.videoId,true))
                let url = `${config.smTargetUrl}${this.$channel}/login?bizId=${this.videoId}&bizToken=${this.$token}&bizUtil=video&partnerId=${this.$store.state.userInfo.un}&rcType=${rcType}&qaId=${qaId}&rcId=${rcId}&targetUrl=${targetUrl}&backUrl=${config.smBackUrl}&source=${source || this.$source}`;
                if (window.terminal.isZxjtApp) {
                  const obj = {
                    'link':url,
                    'linkType':1
                  }
                  this.appLoginState = 'riskPrivate';
                  this.isVerifyAppLogin = true;
                  fun.zxjtAppLink(obj)
                } else {
                  window.location.replace(url)
                }
              }                
          }else{
            if (mode == '0') { // 横屏
              this.isLsPoScreen = 'LsCom'
            } else if (mode == '3') { // 纯净视频
              this.isLsPoScreen = 'PvCom'
            } else {
              this.isLsPoScreen = 'PsCom'
            }
          }
      },
      getLiveBackInfo() {
        // 回看视频数据
        return new Promise(resolve => {
          this.$http.get("/h5live/getBackLiveInfo?vid=" + this.videoId + "&plat=" + fun.getPlatform() + '&newRoom=true').then(
            res => {
              const { data ,code } = res.data;
              if ( code === "000000") {
                const { videoInfo } = data;
                if (videoInfo) {
                  // 付费课程模块预处理
                  this.videoInfo = data;
                  const {mode,channel} = videoInfo;                  
                  resolve(videoInfo)
                  window.sessionStorage.setItem('mode', mode);
                  if (this.$route.params.channel == channel) { //匹配机构号
                    this.rendBack();
                  } else { //机构号不匹配
                    console.log('进入直播间机构号不匹配')
                    fun.toastMessage('进入房间机构号不匹配');
                    setTimeout(()=>{
                      fun.liveBackFun();
                    },2000)
                  }
                }
              }else if (res.data.code == "000001") {//直播间不存在
                fun.toastMessage('直播间不存在');
                setTimeout(()=>{
                    fun.liveBackFun();
                },2000)
              }else{
                console.log('getBackLiveInfo 接口code错误')
                fun.toastMessage('getBackLiveInfo api  error')
                setTimeout(()=>{
                  fun.liveBackFun();
                },2000)
              }
            },
            err => {
              console.log(err);
            }
          );
        })
      },
      handleCoursePre(videoInfo) {
        return new Promise(async resolve => {
          this.coursePreResolve = resolve;
          // 保存观看记录
          this.saveWatchRecord();
          // 新增课程列表tables
          videoInfo.courseId && this.handleTables();
          // 判断是否绑定手机号
          const sessionData = window.sessionStorage.getItem(`${window.channel}CourseSms`)
          if(window.terminal.isZxjtqhApp){
              if(this.$store.state.isYk){
                fun.ykDisposeFun();
              }else{
                this.getCourseDetail();//获取课程详情
              }
          }else{//web wx
            if(this.$store.state.isYk){
                if(sessionData ||this.$store.state.userInfo.hasBindMobile){
                  this.getCourseDetail();//获取课程详情
                }else{
                  this.$store.commit('setGlobalPopupInfo', {
                    ...this.$store.state.globalPopupInfo,
                    type: 0,
                    show: true,
                    title: '您好，欢迎观看本课程',
                    from: this.from,
                  })
                }               
            }else{
                if(this.$store.state.userInfo.hasBindMobile|| sessionData){
                  this.getCourseDetail();//获取课程详情
                }else{
                  this.$store.commit('setGlobalPopupInfo', {
                    ...this.$store.state.globalPopupInfo,
                    type: 0,
                    show: true,
                    title: '您好，欢迎观看本课程',
                    from: this.from,
                  })
                }    
            }
          }
          // if (this.$store.state.userInfo.hasBindMobile) {
          //   this.getCourseDetail();//获取课程详情
          // } else if (window.terminal.isZxjtqhApp) {
          //   this.getCourseDetail();//获取课程详情
          // } else {
          //   this.$store.commit('setGlobalPopupInfo', {
          //     ...this.$store.state.globalPopupInfo,
          //     type: 0,
          //     show: true,
          //     title: '您好，欢迎观看本课程',
          //     from: this.from,
          //   })
          // }
        })
      },
      // 进入直播间（保存课程观看记录）
      saveWatchRecord() {
        const { courseId } = this.videoInfo.videoInfo;
        if (courseId) {
          let courseWatchRecord = JSON.parse(localStorage.getItem(`${this.$channel}courseWatchRecord`)) || {};
          if (courseWatchRecord[courseId]) {
            courseWatchRecord[courseId] = {
             'backId':this.$route.params.id
            }
          } else {
            courseWatchRecord = {
              ...courseWatchRecord,
              [courseId]: {
                'backId':this.$route.params.id
              }
            }
          }
          localStorage.setItem(`${this.$channel}courseWatchRecord`, JSON.stringify(courseWatchRecord));
        }
      },
      // 处理tables
      handleTables() {
        const { tables } = this.videoInfo;
        if (tables && tables.length !== 0) {
          // 有tables字段，首位添加 课程列表
          this.videoInfo.tables = [
            {
              type: 0,
              title: '课程列表',
            },
            ...tables,
          ]
        } else {
          // 无tables字段，添加 课程列表、留言组件
          this.videoInfo.tables = [
            {
              type: 0,
              title: '课程列表',
            },
            {
              type: 1,
              title: '互动聊天',
            },
          ]
        }
      },
      // 获取课程详情
      getCourseDetail() {
        this.$http.get("/h5live/course/getCourseInfo", {
          params: {
            courseId: this.videoInfo.videoInfo.courseId,
          },
        }).then(res => {
          if(res.data.code === "000000") {
            this.courseInfo = res.data.data;
            this.coursePreResolve();
          } else {
            return Promise.reject(res.data);
          }
        }).catch(err => {
          fun.toastMessage('获取课程明细失败');
          console.error(err);
        });
      },
      //腾讯会议直播间校验白名单逻辑
      async tencentWhite() {
        let extParam = sessionStorage.getItem('extParam')
        const params = {
          extParam,
          roomId: this.$route.params.roomid,
          type: '2', //1直播间 2视频库 3 付费课程(建投)
          vid: this.$route.params.id,
        };
        try {
          const dataMsg = await checkWhitelist(params)
          const { code, msg } = dataMsg.data;
          if (code !== "000000") {//验证不成功，展示非白名单提示页
            this.isWhiteTip = true
            return
          }
        } catch (error) {
          console.log(error);
        }
      }
    },
    
  }
</script>

<style scoped="scoped">
  .live-back-box {
    width: 100%;
    height: 100%;
    background: white;
    overflow: hidden;
  }
</style>
